<template>
  <view class="uni-container admin-school-list">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="school_name" label="学校名称" required>
        <uni-easyinput placeholder="请输入学校名称" v-model="formData.school_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="city_code" label="学校地址" required>
        <uni-data-picker v-model="formData.city_code" placeholder="请选择地址" popup-title="请选择城市" :step-searh="true" self-field="code" parent-field="parent_code" @change="(e)=>formData.city_id_array=e.detail.value" collection="admin-city-china" field="name as text, code as value" orderby="value asc"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="school_icon" label="学校图标" required class="alignFlexStart">
        <uni-file-picker ref="files" :auto-upload="false" @select="(e)=>fileList=e" @delete="()=>fileList==null" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.school_icon"></uni-file-picker>
      </uni-forms-item>

      <uni-forms-item name="school_address_xy" label="地图经纬坐标" required>
        <div class="flexStyleBetween" style="width:100%">
          <div class="flexStyle" style="width: 60%;">
              <uni-easyinput placeholder="请输入经纬度，经度前纬度后逗号分割" v-model="school_address_xy" trim="both"></uni-easyinput>
          </div>
            <div class="flexStyle addSelectBox" @click="goToPage('https://lbs.qq.com/getPoint/#')">
              <uni-icons type="location" size="20" color="#2979ff"></uni-icons>
              <div>点我获取信息</div>
            </div>
        </div>
      </uni-forms-item>
      <uni-forms-item name="school_address_info" label="地图详细地址" required>
        <uni-easyinput placeholder="请输入学校所在地图上的详细地址" v-model="formData.school_address_info" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="school_poi_id" label="地图POI ID">
        <uni-easyinput placeholder="请输入学校所在地图上的POI ID" v-model="formData.school_poi_id" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="学校描述" class="alignFlexStart">
        <uni-easyinput type="textarea" placeholder="请输入学校描述" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="enable_status" label="启用或关闭">
        <switch style="transform: scale(0.8);" @change="binddata('enable_status', $event.detail.value)" :checked="formData.enable_status"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<style lang="stylus" scoped>
.addSelectBox
  font-size: 12px
  cursor pointer
  user-select: none
  color: #2979ff
</style>

<script>
  import { validator } from '../../js_sdk/validator/admin-school-list.js';


  const adminFilesMG = uniCloud.importObject('admin-files-manage',{
      customUI:true
  }) 

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'admin-school-list';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "school_name": "",
        "school_icon": [],
        "city_code": '',
        "city_id_array":[],
        "school_address_xy": [],
        "school_address_info": "",
        "school_poi_id": "",
        "description": "",
        "enable_status": true
      }
      return {
        school_address_xy:``,
        fileList:null,

        formData,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      'school_address_xy':{
        handler:function(val){
          const list=val.split(',');
          const value=[];
          if(list.length==2){
              for(let i=0;i<list.length;i++){
                const it=list[i].trim();
                if(/^\d+\.\d+?$/.test(it)){
                  value.push(parseFloat(it))
                }
              }
              if(value.length===2){
                return this.formData.school_address_xy=value;
              }
          }
          this.formData.school_address_xy=[];
        },
        immediate:true
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      goToPage(path){
        window.open(path)
      },


      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then(async (res) => {

          if(res.school_icon.length===0&&this.fileList==null){
             return this.$toast.error(`请上传学校图标`, {
                timeout: 2000,
                hideProgressBar: true,
              });
          }

            if(this.fileList!=null){
        
            await adminFilesMG.removeFile({
                table:`admin-school-list`,
                id:[this.formDataId],
                field:`school_icon`
              });

              res.school_icon= await this.$refs.files.upload();
            }

            res.city_id_array=this.formData.city_id_array

            console.log(res)

          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("school_name,school_icon,city_id_array,city_code,school_address_xy,school_address_info,school_poi_id,description,enable_status").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            this.school_address_xy=data.school_address_xy.join(',')
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
